#!/bin/bash

unalias -a
unset META_LAYER_ROOT

# 初始化环境变量
META_LAYER_ROOT=${META_LAYER_ROOT:-meta-aw}
ROOTOE=$PWD

if [[ ! -d "${ROOTOE}/${META_LAYER_ROOT}" ]]; then
    echo "[ERROR] 当前目录下未找到 ${META_LAYER_ROOT} 目录"
    return 1
fi

if [[ -z "$DISTRO" || -z "$MACHINE" ]]; then
    echo "[ERROR] 请设置 DISTRO 和 MACHINE 环境变量"
    return 1
fi

BUILD_DIR=$(realpath -m "../build-$MACHINE-$DISTRO")  # 规范化路径

TEMPLATECONF=${ROOTOE}/${META_LAYER_ROOT}/meta-aw-riscv-distro/conf/templates/default \
    source ${ROOTOE}/poky/oe-init-build-env ${BUILD_DIR}

if [ -z "$(grep '^MACHINE =' conf/local.conf)" ]; then
    # Apply selected MACHINE in local conf file
    sed -e 's/^\(MACHINE.*\)$/#\1\nMACHINE = "'"$MACHINE"'"/' -i conf/local.conf
else
    echo "[WARNING] MACHINE is already set in local.conf. Nothing done..."
fi
if [ -z "$(grep '^DISTRO =' conf/local.conf)" ]; then
    # Apply selected DISTRO in local conf file
    sed -e 's/^\(DISTRO.*\)$/#\1\nDISTRO = "'"$DISTRO"'"/' -i conf/local.conf
else
    echo "[WARNING] DISTRO is already set in local.conf. Nothing done..."
fi

echo "[INFO] 构建环境已设置:"
echo "       ROOT: ${ROOTOE}"
echo " BUILD_DIR: ${BUILD_DIR}"
echo "     DISTRO: ${DISTRO}"
echo "    MACHINE: ${MACHINE}"
